<?php

if (!defined('JB_ENABLED_PLUGINS')) {
	define ('JB_ENABLED_PLUGINS', '');
}

if (!defined('JB_PLUGIN_CONFIG')) {
	define ('JB_PLUGIN_CONFIG', '');
}

if (!defined('JB_PLUGIN_SWITCH')) {
	define ('JB_PLUGIN_SWITCH', '');
}


$JB_callbacks = array();
$_JB_PLUGINS = array();

JBPLUG_require_plugins();

$_JB_PLUGIN_CONFIG = unserialize(JB_PLUGIN_CONFIG);

###############################################################

class JB_Plugins {

	
	var $class_name;

	function JB_Plugins () {
		
		
	}

	function get_description() {
		return 'please implement get_description() method for your module.';

	}

	function get_name() {
		return 'please implement get_name() method for your module.';

	}

	function get_author() {
		return 'please implement get_author() method for your module.';

	}

	function get_version() {
		return 'please implement get_version() method for your module.';

	}

	function get_version_compatible() {
		return '3.0.0+';

	}

	function config_form() {
		echo "please implement config_form() method in your plugin<br>";

	}

	function save_config() {
		echo "please save_config() method in your plugin<br>";

	}


	
	function is_enabled() {
		return true;

	}

	function enable($class_name='JB_Plugins') {
		if ($class_name=='JB_Plugins') {
			echo "please implement enable() method in your plugin. See the example modules to see how it is done<br>";
			return false;
		}

		
		if (strlen(JB_ENABLED_PLUGINS) > 0 ) {
			$enabled_plugins = explode (',', JB_ENABLED_PLUGINS);
			
			$enabled_plugins[] = $class_name;
			$enabled_plugins = implode (',', $enabled_plugins);
		} else {
			$enabled_plugins = $class_name;
		}

	
		JBPLUG_update_enabled_plugins($enabled_plugins);
		JBPLUG_merge_english_default_files();

	}

	function disable($class_name='JB_Plugins') {
		if ($class_name=='JB_Plugins') {
			echo "please implement disable() method in your plugin. See the example modules to see how it is done<br>";
			return;
		}

		if (strlen(JB_ENABLED_PLUGINS) > 0 ) {
			$enabled_plugins = explode (',', JB_ENABLED_PLUGINS);
			
			foreach ($enabled_plugins as $plugin) {
				if ($plugin != $class_name) {
					$new_plugins[] = $plugin;

				}
			}
			if (sizeof($new_plugins)>0) {
				$enabled_plugins = implode (',', $new_plugins);
			} else {
				$enabled_plugins = '';
			}
		
			JBPLUG_update_enabled_plugins($enabled_plugins);
		} 

		

	}

}



##########################################################################################


function JBPLUG_update_enabled_plugins($enabled_plugins=JB_ENABLED_PLUGINS) {

	// load the config in

	$config_dir = dirname(__FILE__);
	$config_dir = preg_split ('%[/\\\]%', $config_dir);
	$blank = array_pop($config_dir);
	$config_dir = implode('/', $config_dir);
	$config_dir = $config_dir."/";


	$filename = $config_dir."config.php";
	$handle  = fopen($filename, "rb");
	$contents = fread($handle , filesize($filename));
	fclose ($handle);

	if ($enabled_plugins != JB_ENABLED_PLUGINS) {

		// change the JB_ENABLED_PLUGINS constant
		
		$handle  = fopen($filename, "w");

		$contents = preg_replace ( "/[ ]*define\('JB_ENABLED_PLUGINS',[ ]*'[^']*'\);[ ]*/U", "define('JB_ENABLED_PLUGINS', '".$enabled_plugins."');", $contents) ;
	
		fwrite($handle , $contents);
		fclose ($handle);
	}
}

function JBPLUG_update_plugin_config($config=JB_PLUGIN_CONFIG) {

	// load the config in

	$config_dir = dirname(__FILE__);
	$config_dir = preg_split ('%[/\\\]%', $config_dir);
	$blank = array_pop($config_dir);
	$config_dir = implode('/', $config_dir);
	$config_dir = $config_dir."/";


	$filename = $config_dir."config.php";
	$handle  = fopen($filename, "rb");
	$contents = fread($handle , filesize($filename));
	fclose ($handle);
	
	$handle  = fopen($filename, "w");

	$new_contents = preg_replace ( "/[ ]*define\('JB_PLUGIN_CONFIG',[ ]*'[^']*'\);[ ]*/U", "define('JB_PLUGIN_CONFIG', '".$config."');", $contents) ;


	fwrite($handle , $new_contents);
	fclose ($handle);
}

# Require all the enabled plugins.

function JBPLUG_require_plugins() {

	global $_JB_PLUGINS;

	if (JB_PLUGIN_SWITCH != 'YES') {
		
		RETURN false;
	}

	$dir = dirname(__FILE__)."/plugins/";

	if (JB_ENABLED_PLUGINS!='') {
		$enabled_plugins = explode(',', JB_ENABLED_PLUGINS);
		if (sizeof ($enabled_plugins) > 0) {
			foreach ($enabled_plugins as $plugin) {
				$plugin_file = $dir.$plugin."/$plugin.php";
				if (file_exists($plugin_file)) {
					include_once($plugin_file);
				} else {
					echo "Could not require ".$plugin_file."<br>";
				}
			}
		}
	}


}

#####################################################################
# Require all plugins, enabled or not enabled.


function JBPLUG_require_all_plugins() {

	if (JB_PLUGIN_SWITCH!='YES') {

		return;
	}

	global $_JB_PLUGINS;

	$dir = dirname(__FILE__)."/plugins/";
	if (is_dir($dir)) {
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				
				if ((filetype($dir . $file)=='dir') && ($file!='.') && ($file!='..')) {
					// include the main class...
					$dir2 = $dir . $file;

					$temp = explode('.', $file2);
					$ext = array_pop($temp);
					
				
					$temp = preg_split ('%[/\\\]%', $dir2);
					$name = array_pop($temp);

					$name = "$name.php";

					require_once ($dir2 .'/'. $name);
					

				}
			}
			closedir($dh);
		}
	}


}

###################################################################
# This function will call all the callbacks that were registered by enabled plugins
/*
$callback_name - the name of the call back
Then arbitary arguments of global variable names

*/
function JBPLUG_do_callback($callback_name, &$A) {
	global $_JB_PLUGINS;
	
	global $JB_callbacks;
	// get the hooks list
	if (!isset($JB_callbacks[$callback_name])) return false; // no hooks are set
	$hooks = $JB_callbacks[$callback_name];

	// the argument $A is passed by reference
	if ($A!==false) {

		$args .= $comma.'$A';
		$comma = ', ';

	}


	// build the argument variables
	for ($i=2; $i < func_num_args(); $i++) {
		
		

		$argn = chr(65+$i); // create the arg name
		$$argn = func_get_arg($i);
		
		
		$args .= $comma.'$'.$argn;
		$comma = ', ';
	}

	if (sizeof($hooks) > 0) {
		foreach ($hooks as $hook) {
		
			if ($args!='') { // the callback has some arguments, use eval()
				$the_call = '$_JB_PLUGINS["'.$hook['call'][0].'"]->'.$hook["call"][1].'('.$args.');';
				
				eval ($the_call);

			} else { // the callback has no arguments, use function variables
				$_JB_PLUGINS[$hook['call'][0]]->$hook["call"][1]();
				//call_user_func ($hook['call']); // alternative way to call
			}
			
		}
		return true;

	}
	return false; // no callbacks were registered
	
	
}

##################################################################
# Register a callback and sort it by priority
# Each place on the code where a callback is registered is called a 'hook'
function JBPLUG_register_callback ($callback_name, $call, $priority=0) {

	global $JB_callbacks;
	// there could be several functions for each callback
	$hook['call'] = $call;
	$hook['priority'] = $priority;
	$JB_callbacks[$callback_name][] = $hook;
	// sort the callback list according to priority
	usort($JB_callbacks[$callback_name], "JBPLUG_comp_priority");
	
}

function JBPLUG_comp_priority($a, $b) {
        return strnatcasecmp($a["priority"], $b["priority"]);
}



########################################

function JBPLUG_list_plugins() {

	global $_JB_PLUGINS;


	?>
	<script language="JavaScript" type="text/javascript">

	function confirmLink(theLink, theConfirmMsg) {

       if (theConfirmMsg == '' || typeof(window.opera) != 'undefined') {
           return true;
       }

       var is_confirmed = confirm(theConfirmMsg + '\n');
       if (is_confirmed) {
           theLink.href += '&is_js_confirmed=1';
       }

       return is_confirmed;
	}
	</script>
	<table width="100%">
	<tr><td valign="top">
	<table width="100%" border="0" cellSpacing="1" cellPadding="3" bgColor="#d9d9d9" width="400" >
	<tr bgColor="#eaeaea">
	<td><b><font size="2">Plugin Name</b></font></td>
	<td><b><font size="2">Description</b></font></td>
	<td><b><font size="2">Author</b></font></td>
	<td><b><font size="2">Version</b></font></td>
	<td><b><font size="2">Status</b></font></td>
	<td><b><font size="2">&nbsp;</b></font></td>
	</tr>
	<?php

		foreach ($_JB_PLUGINS as $obj_key => $plugin) {
			?>
			<tr <?php if ($obj_key==$_REQUEST['plugin'])  { echo ' bgColor="#FFFF99" ';} else echo ' bgColor="#ffffff" '; ?> onmouseover="old_bg=this.getAttribute('bgcolor');this.setAttribute('bgcolor', '#FBFDDB', 0);" onmouseout="this.setAttribute('bgcolor', old_bg, 0);">
			<td><?php echo $plugin->get_name(); ?></td>
			<td><?php echo $plugin->get_description(); ?></td>
			<td><?php echo $plugin->get_author(); ?></td>
			<td><?php echo $plugin->get_version(); ?></td>
			<td><?php 
				if ($plugin->is_enabled()) {
						echo "<font color='green'><IMG SRC='../admin/active.gif' WIDTH='16' HEIGHT='16' BORDER='0' ALT='Enabled'></font>";

					} else {
						echo "<font color='red'><IMG SRC='../admin/notactive.gif' WIDTH='16' HEIGHT='16' BORDER='0' ALT='Not Enabled'></font>";

					}
				?></td>
			<td><?php

					if ($plugin->is_enabled()) {
					//	echo "Enabled";
						echo "<input type='button' style='font-size: 10px;' value='Disable' onclick=\"if (!confirmLink(this, 'Disable, are you sure?')) return false;window.location='".$_SERVER['PHP_SELF']."?plugin=".$obj_key."&action=disable'\">";
						echo "<input style='font-size: 10px;' type='button' value='Configure' onclick=\"window.location='".$_SERVER['PHP_SELF']."?plugin=".$obj_key."'\">";

					} else {
						//echo "Not Enabled";
						echo "<input style='font-size: 10px;' type='button' value='Enable' onclick=\"if (!confirmLink(this, 'Enable, are you sure?')) return false; window.location='".$_SERVER['PHP_SELF']."?plugin=".$obj_key."&action=enable'\">";

					}


					
				?></td>
			</tr>
			<?php

		}
		?>
		</table>
		</td>
		<td valign="top">
		<?php
			if ($_REQUEST['plugin']) {
				$_JB_PLUGINS[$_REQUEST['plugin']]->config_form();
			}
		
		?>
		</td>
		</table>
		
		<?php
}

function JBPLUG_save_config_variables($class_name) {

	for ($count=1; $count < func_num_args(); $count++) {
		
		$vars[func_get_arg($count)] = trim($_REQUEST[func_get_arg($count)]);
	}
	if (JB_PLUGIN_CONFIG!='') {
		$config = unserialize(JB_PLUGIN_CONFIG);
	}

	$config[$class_name] = $vars;

	$config = serialize($config);
	JBPLUG_update_plugin_config($config);


}

function JBPLUG_load_config_variables($class_name) {

	for ($count=1; $count < func_num_args(); $count++) {

		echo func_get_arg($count)."<br>";

	}


}

function JBPLUG_append_english_default_labels() {

	global $_JB_PLUGINS;
	global $label;

	foreach ($_JB_PLUGINS as $class => $obj) {
		
		$file = dirname(__FILE__)."/plugins/$class/lang/english_default.php";
		if (file_exists($file)) {
			require ($file);
		} else {
			echo "does not exist: ".$file."<br>";
		}

	}


}

////

function JBPLUG_append_english_default_source(&$source_code) {

	global $_JB_PLUGINS;

	foreach ($_JB_PLUGINS as $class => $obj) {

		$file = dirname(__FILE__)."/plugins/$class/lang/english_default.php";
		
		if (file_exists($file)) {
			$handle = fopen($file, "rb");
			while ($buffer= fgets($handle, 4096)) {
				if (preg_match ('/ *\$label\[.([A-z0-9]+).\].*/', $buffer, $m)) {
					$source_code[$m[1]] = $buffer;
				}
			}
		}

	}
}

///////////////

function JBPLUG_merge_english_default_files() {

	JBPLUG_require_all_plugins();

	global $_JB_PLUGINS;

	// get active languages

	$sql = "SELECT * FROM lang where is_active='Y' ";
	$result = JB_mysql_query ($sql) or die (mysql_error());

	// compute the $lang_dir
	$lang_dir = dirname(__FILE__);
	$lang_dir = preg_split ('%[/\\\]%', $lang_dir);
	$blank = array_pop($lang_dir);
	$lang_dir = implode('/', $lang_dir);
	$lang_dir = $lang_dir."/lang/";
	

	// Now merge the english_default.php strings with the language files

	while ($row = mysql_fetch_array($result)) {

		/// for each of the plugins
		foreach ($_JB_PLUGINS as $class => $obj) {

			$english_default =  dirname(__FILE__)."/plugins/$class/lang/english_default.php";
		
			if (!file_exists($english_default)) {
				continue;
			}


			$lang_filename=$row['lang_filename'];

			if (is_writable("$lang_dir$lang_filename")) {
				//echo "- lang/$lang_filename file is writeable. (OK)<br>";
				$f1 = stat ("$lang_dir$lang_filename");
				$f2 = stat ($english_default);
				//if ($f2['mtime'] > $f1['mtime']) {
				if (true) { // always force a merge

					echo "Merging language strings for $lang_filename...";


					include ($english_default); // the module's english default
					include ($lang_dir."english_default.php"); // the lang/english_default
					$source_label = $label; // default english labels
					include ($lang_dir.$lang_filename);
					$dest_label = $label; // dest labels

					$out = "<?php\n";
					foreach ($source_label as $key=>$val) {
						//$source_label[$key] = addslashes($dest_label[$key]);
						$source_label[$key] = str_replace("'", "\'",$dest_label[$key] );
						$out .= "\$label['$key']='". $source_label[$key]."'; \n";
					}
					$out .= "?>\n"; 
					
					$handler = fopen ($lang_dir.$lang_filename, "w");
					fputs ($handler, $out);
					fclose ($handler);

					echo " Done.<br>";

				}

			} else {
				echo "<font color='red'><b>- lang/$lang_filename file is not writable. Give write permissions (666) to lang/$lang_filename file and then disable & re-enable this plugin</b></font><br>";
			}

		}

	}


}



?>